<template>    
  <AppCover
    section="article"
    :bgURL="coverURL"
    :bgPrURL="coverPrURL"
    :articleTitle="articleTitle"
    :articleDate="articleDate"
    :articleClassify="articleClassify"
  />
  <article id="Article">
    <div 
      class="article_info"
      v-show="articleData && articleData.author || articleData && articleData.source"
    >
      <span class="author" v-show="articleData && articleData.author">{{ articleData && articleData.author }}</span>
      <span class="source" v-show="articleData && articleData.source">{{ articleData && articleData.source }}</span>
    </div>
    <div class="article-main" v-html="articleData && articleData.content"></div>
    <div class="like" @click="likeHandler(articleId)">
      <span 
        class="iconfont icon-xihuan1" 
        style="color:red"
        v-show="isLike === false"
      >
      </span>
      <span 
        class="iconfont icon-xihuan"
        style="color:red"
        v-show="isLike === true"
      >
      </span>
      <span 
        class="num"
        :class="{num_margin: likeCount > 0}"
      >
        {{ likeCount === 0 ? '' : likeCount  }}
      </span>
    </div>    
    <p 
      class="article_views"
      v-show="articleData && articleData.views > 0"
    >
      阅读：{{ articleData && articleData.views }}
    </p>
    <AppMsgBoard :section="sectionVal" v-show="articleData && articleData.message"/>    
  </article>
  <!-- 图片预览v-viewer -->
  <viewer :images="images"></viewer>
  <AppNav />
  <AppFooter />
</template>

<script>
import AppNav from '@/components/AppNav'
import AppCover from '@/components/AppCover'
import AppFooter from '@/components/AppFooter'
import AppMsgBoard from '@/components/AppMsgBoard'

export default {
  name: 'Article',
  components: { AppNav, AppCover, AppFooter, AppMsgBoard },
  data(){
    return{
      sectionVal: 'article'+this.$route.params.id,
      articleData: null,
      likeCount: 0,
      ip: '',
      likeIPs: [],
      images: [],
      $viewer: null
    }
  },
  created(){
    this.getData()
    this.ip = returnCitySN["cip"]
  },
  mounted(){
    this.clickImg()
  },
  computed: {
    coverURL(){
      return this.articleData && this.articleData.cover
    },
    coverPrURL(){
      return this.articleData && this.articleData.coverPr
    },
    articleTitle(){
      return this.articleData && this.articleData.title
    },
    articleDate(){
      return this.articleData && this.articleData.date
    },
    articleClassify(){
      return this.articleData && this.articleData.classify
    },
    articleId(){
      return this.articleData && this.articleData._id
    },
    isLike(){
      if(!this.ip || !this.likeIPs) return false
      // console.log(this.ip, this.likeIPs);
      return this.likeIPs && this.likeIPs.indexOf(this.ip) != -1
    }
  },
  // 离开页面时把图片预览插件关掉
  beforeRouteLeave(to, from, next) {
    this.$viewer && this.$viewer.destroy()
    next()
  },
  methods: {
    // 点击富文本内容里的img
    clickImg(){
      let articleMain = document.getElementsByClassName('article-main')[0]
      articleMain.addEventListener('click', (e) => {
        if(e.target.nodeName == 'IMG'){          
          let imgSrc = e.target.src
          // 获取当前页面地址，如http://localhost:8080/admin/index
          let wPath = window.document.location.href;
          // 获取当前页面主机地址之后的目录，如：/admin/index
          let pathName =  this.$route.path;
          let pos = wPath.indexOf(pathName);
          // 获取主机地址，如：http://localhost:8080
          let localhostPath = wPath.substring(0, pos);
          // 去掉主机路径，然后查找照片索引
          let reg = new RegExp(localhostPath)
          imgSrc = imgSrc.replace(reg, '')
          let index = this.images.indexOf(imgSrc)
          
          this.show(index)
        }
      })
    },
    show (imgIndex) {
      this.$viewer = this.$viewerApi({
        images: this.images,
        options:{initialViewIndex: imgIndex}
      })
    },
    // 点赞
    async likeHandler(id){
      // console.log(id + "-" + returnCitySN["cip"])
      this.ip = returnCitySN["cip"]
      let {data} = await this.$axios({
        method: 'post',
        url: '/article/like',
        data: {
          id,
          ip: this.ip
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      // console.log("likeHandler:", data.data);
      this.likeIPs = data.data
      this.likeCount = data.data.length
    },
    // 获取文章数据
    async getData() {
      // console.log("sectionVal: ", this.sectionVal);
      let {data} = await this.$axios({
        method: 'post',
        url: '/article/single',
        data: {
          _id: this.$route.params.id
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      this.articleData = data.data
      this.likeIPs = this.articleData.likes
      this.likeCount = this.articleData.likes.length
      // console.log("singleData: ", this.articleData.content)

      this.getImgSrc(this.articleData.content)
    },
    // 获取html文本里的img.src
    getImgSrc(htmlStr){
      let imgStrs = htmlStr.match(/<img.*?>/g)
      if(imgStrs){
        // 获取每个img url
        let urls = imgStrs.map(url=>{
          return url.match(/\ssrc=['"](.*?)['"]/)[1]
        })
        this.images = urls
      }else{
        console.log('没有图片')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@pageWidth: 50rem;

.viewer-wrapper {
  position: relative;
  background: #333;
  height: 100%;
}
#Article{
  width: @pageWidth;
  margin: 3rem auto;
  
  .article-main{
    -webkit-hyphens: auto;
    -ms-hyphens: auto;
    hyphens: auto;
    padding: 0 20px;
    color: #000;
    letter-spacing: 0.08em;
    font-weight: 100;
    font-size: 18px;
    line-height: 30px;
    line-break: anywhere;
    :deep(img){
      cursor: zoom-in;
    }
    :deep(pre) {
      margin: 1.64em 0;
      padding: 10px;
      border: none;
      overflow: auto;
      -webkit-overflow-scrolling: touch;
      line-height: 1.5;
      font-size: 0.9em;
      font-family: 'Source Code Pro', Consolas, Menlo, Monaco, 'Courier New', monospace;
      color: #4c4c4c;
      background-color: #f9f9f7;
      code {
        color: #4c4c4c;
        background: none;
        padding: 0;
      }
    }
    :deep(ul){
      list-style:square;
      list-style-position:inside;
      li{
        padding: .5em 0;
      }
    }

    :deep(p), :deep(ul) {
      // text-indent: 2em;
      margin-bottom: 1.12em;
      -webkit-hyphens: auto;
      -ms-hyphens: auto;
      hyphens: auto;
    }

    :deep(h2){
      font-size: 1.42em;
    }

    :deep(hr) {
      display: block;
      border: 0;
      margin: 2.24em auto;
      &::after{
        color: rgba(0, 0, 0, 0.2);
        font-size: 1.1em;
        display: block;
        content: "* * *";
        text-align: center;
      }
    }

    :deep(a){
      color: rgba(0, 0, 0, 0.98);
      word-wrap: break-word;
      text-decoration: none;
      border-bottom: 1px solid rgba(0, 0, 0, 0.26);
      &:hover{
        color: #0061e6;
        border-bottom: 1px solid #0061e6;
      }
    }
  }

  .article_info{
    text-align: center;
    font-size: 12px;
    margin-bottom: 2rem;
    span{
      line-height: 30px;
      &:nth-child(2)::before{
        content: " / ";
        font-size: 10px;
        color: rgba(0, 0, 0, 0.1);
        margin: 0 4px;
      }
    }
  }
  .article_views{
    font-size: 14px;
    color: #7f7f7f;
    text-align: right;
    padding-right: 15px;
    margin-top: 2rem;
  }
  .like{
    width: 130px;
    height: 37px;
    border: 1px solid red;
    border-radius: 24px;
    -moz-border-radius: 24px;
    -webkit-border-radius: 24px;
    -o-border-radius: 24px;
    margin: 4.5rem auto 3rem;
    cursor: pointer;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    .iconfont{
      line-height: 37px;      
    }
    .icon-xihuan1{
      font-size: 24px;
    }
    .icon-xihuan{
      font-size: 24px;
    }
    .num{
      font-size: 16px;
      vertical-align: 2px;      
      color: #dd0000;
    }
    .num_margin{
      margin-left: 5px;
    }
  }
}



/* 很小的设备（手机等，小于 600px） */
@media only screen and (max-width: 600px) { 
  #Article {
    max-width: 100vw;
  }
}

/* 比较小的设备（竖屏的平板，屏幕较大的手机等, 大于 600px） */
@media only screen and (min-width: 600px) { 
  #Article {
    min-width: 34rem;
  }
}

/* 中型大小设备（横屏的平板, 大于 768px） */
@media only screen and (min-width: 768px) { 
  #Article {
    min-width: 38rem
  }
}

/* 大型设备（电脑, 大于 992px） */
@media only screen and (min-width: 992px) { 
  #Article {
    min-width: 44rem;
  }
}

/* 超大型设备（大尺寸电脑屏幕, 大于 1200px） */
@media only screen and (min-width: 1200px) { 
  #Article {
    min-width: 50rem;
  }
}
</style>